package com.everflourish.yeah100.act.markingsystem;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.act.questionlib.HackyViewPager;
import com.everflourish.yeah100.adapter.ImageViewPagerAdapter;
import com.everflourish.yeah100.adapter.ObjectAnswerAdapter;
import com.everflourish.yeah100.adapter.SubjectAnswerAdapter;
import com.everflourish.yeah100.entity.clazz.ClassManage;
import com.everflourish.yeah100.entity.marking.ObjectAnswer;
import com.everflourish.yeah100.entity.marking.ProofreadStudentAnswer;
import com.everflourish.yeah100.entity.marking.Standard;
import com.everflourish.yeah100.entity.marking.Student;
import com.everflourish.yeah100.entity.marking.SubjectAnswer;
import com.everflourish.yeah100.entity.marking.Topic;
import com.everflourish.yeah100.http.MarkingSystemRequest;
import com.everflourish.yeah100.ui.ExpandableGridView;
import com.everflourish.yeah100.ui.dialog.KeyboardWindow;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.ui.dialog.SingleAnswerDialog;
import com.everflourish.yeah100.utils.AnswerUtil;
import com.everflourish.yeah100.utils.KeyBoardUtils;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.ResourcesUtil;
import com.everflourish.yeah100.utils.StringUtil;
import com.everflourish.yeah100.utils.TopicUtil;
import com.everflourish.yeah100.utils.collections.TopicCollections;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.everflourish.yeah100.utils.constant.StudentStatus;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 作者：Created by liqisi on 2016/11/29.
 * 时间：2016/11/29
 */
public class ProofreadCorrectActivity extends BaseActivity implements View.OnClickListener {

    private ImageViewPagerAdapter adapter;
    private HackyViewPager pager;
    private EditText mStudentNoTv, mStudentNameTv;
    private List<String> imageList;
    private ExpandableGridView mStudentObjectAnswerGv, mStudentSubjectAnswerGv;
    private ObjectAnswerAdapter mObjectAdapter;
    private SubjectAnswerAdapter mSubjectAdapter;
    private List<ObjectAnswer> mObjectList;
    private ArrayList<SubjectAnswer> mSubjectList;
    private List<Topic> mTopics;
    public ArrayList<Map<String, Object>> mStaList;
    private MarkingSystemRequest mRequest;
    private LoadDialog mLoadDialog;
    private String mExaminationId;
    private String mStudentNo, mStudentTempNo, mStudentTempName, mStudentName;
    private ProofreadStudentAnswer mProofreadStudentAnswer;
    private KeyboardWindow mPopupWindow;
    private int index;
    private List<ClassManage> mClassManages;
    private String emptyStudentAnswer;
    private Student mStudent;
    private String mExamLastModifiedTime;
    private Button mCommitBt;
    private RelativeLayout mWeightAdjustRl;
    private FrameLayout mProofreadImageLl;
    private boolean weightFlag = false;
    private ImageView mStretchIv;
    private int imageIndex = 1;  // 图片位置
    private int totalNum;  // 图片总数
    private TextView mImageSelectTv;
    private boolean isInitDataRequest = true;
    private boolean isUpdate = false; //  答案是否有更新

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_proofread_correct);
        initData();
        initView();
        configView();
    }

    private void initData() {
        mExaminationId = getIntent().getStringExtra("examinationId");
        mStudentTempNo = mStudentNo = getIntent().getStringExtra("studentNo");
        mStudentTempName = mStudentName = getIntent().getStringExtra("studentName");
        mExamLastModifiedTime = getIntent().getStringExtra("lastModifiedTime");
        imageList = (ArrayList<String>) getIntent().getSerializableExtra("pictureUrl");

        mStaList = new ArrayList<>();
        mObjectList = new ArrayList<>();
        mSubjectList = new ArrayList<>();
        mRequest = MarkingSystemRequest.getInstance();
        mObjectAdapter = new ObjectAnswerAdapter(mContext, mObjectList, mStaList);
        mSubjectAdapter = new SubjectAnswerAdapter(mContext, null, mSubjectList);
    }

    private void initView() {
        pager = (HackyViewPager) findViewById(R.id.proofread_pager);
        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                imageIndex = position + 1;
                mImageSelectTv.setText(imageIndex + "/" + totalNum);
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        pager.setLocked(false);
        adapter = new ImageViewPagerAdapter(getSupportFragmentManager(), imageList, false);
        pager.setAdapter(adapter);

        mCommitBt = (Button) findViewById(R.id.commit_answer_tv);
        mStudentNameTv = (EditText) findViewById(R.id.proofread_student_name);

        mStudentNoTv = (EditText) findViewById(R.id.proofread_student_no);
        mWeightAdjustRl = (RelativeLayout) findViewById(R.id.proofread_weight_rl);
        mStretchIv = (ImageView) findViewById(R.id.proofread_stretch_iv);
        mProofreadImageLl = (FrameLayout) findViewById(R.id.proofread_image_ll);
        mStudentObjectAnswerGv = (ExpandableGridView) findViewById(R.id.proofread_student_object);
        mStudentSubjectAnswerGv = (ExpandableGridView) findViewById(R.id.proofread_student_subject);
    }

    private void configView() {
        if (imageList != null) {
            totalNum = imageList.size();
        }
        mImageSelectTv = (TextView) findViewById(R.id.proofread_image_index_tv);
        mImageSelectTv.setText(imageIndex + "/" + totalNum);
        mStudentObjectAnswerGv.setAdapter(mObjectAdapter);
        mStudentSubjectAnswerGv.setAdapter(mSubjectAdapter);

        mCommitBt.setOnClickListener(this);
        mWeightAdjustRl.setOnClickListener(this);
        mStudentObjectAnswerGv.setOnItemClickListener(itemObjectClickListener);
        mStudentSubjectAnswerGv.setOnItemClickListener(itemSubjectClickListener);

        mStudentNameTv.setText(mStudentName);
        mStudentNameTv.setSelection(mStudentName.length());
        mStudentNoTv.setText(mStudentNo);
        mStudentNoTv.setSelection(mStudentNo.length());
        KeyBoardUtils.closeKeybord(mStudentNoTv, mContext);

        getStudentAnswersRequest();
    }

    /**
     * 客观题答案item监听
     */
    AdapterView.OnItemClickListener itemObjectClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            showAlterDialog(position);
        }
    };

    /**
     * 主观题答案item监听
     */
    AdapterView.OnItemClickListener itemSubjectClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            showKeyboard(position);
        }
    };

    /**
     * 显示客观题答案修改对话框
     *
     * @param position
     */
    private void showAlterDialog(final int position) {
        List<String> items = new ArrayList<String>();
        items.add("A");
        items.add("B");
        items.add("C");
        items.add("D");
        items.add("E");
        items.add("F");
        items.add("G");
        items.add("H");

        // 当点击了item后，弹出修改对话框
        boolean isSingle = true;
        int serialNumber = mObjectList.get(position).getSerialNumber();
        final String answer = mObjectList.get(position).getAnswer();
        int type = AnswerUtil.getCurrentTopicType(serialNumber, mTopics);
        String title = null;
        if (type == 1) {// 单选
            isSingle = true;
            title = "第" + serialNumber + "题(单选)： " + answer;
        } else if (type == 2) {// 多选
            isSingle = false;
            title = "第" + serialNumber + "题(多选)：" + answer;
        }
        final SingleAnswerDialog answerDialog = new SingleAnswerDialog(
                mContext, title, null, isSingle, false);
        answerDialog.setIsCancelShrinkFlag(true);
        answerDialog.setItems(items, answer,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 单选题
                        setPositionAnswer(position, answerDialog, answer);
                        if (position < mObjectList.size() - 1) {
                            showAlterDialog(position + 1);
                            dialog.dismiss();
                        } else {
                            dialog.dismiss();
                        }
                    }
                });
        String confirmButtonText = "下一题";
        if (position == mObjectList.size() - 1) {
            confirmButtonText = "完成";
        }
        answerDialog.setOnConfirmButton(confirmButtonText,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPositionAnswer(position, answerDialog, answer);
                        dialog.dismiss();
                        if (position < mObjectList.size() - 1) {
                            showAlterDialog(position + 1);
                        }
                    }
                });
        String cancelButtonText = "上一题";
        if (position == 0) {
            cancelButtonText = "完成";
        }
        answerDialog.setOnCancelButton(cancelButtonText,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPositionAnswer(position, answerDialog, answer);
                        dialog.dismiss();
                        if (position > 0) {
                            showAlterDialog(position - 1);
                        }
                    }
                });
        answerDialog.show();
    }

    /**
     * 准备显示主观题分数
     *
     * @param position
     */
    private void showKeyboard(int position) {
        ArrayList<SubjectAnswer> tempList = mSubjectList;
        List<String> items = selectSubjectScore(position);
        String answer = tempList.get(position).getAnswer();
        showKeyboardDialog(items, position, answer, tempList);
    }

    /**
     * 主观题分数items
     *
     * @param position
     * @return
     */
    private List<String> selectSubjectScore(int position) {
        List<String> items = null;
        float point = 0;
        int serialNum = mSubjectList.get(position).getSerialNumber();
        for (int i = 0; i < mTopics.size(); i++) {
            Topic t = mTopics.get(i);
            if (t.getTopicEnd() >= serialNum) {
                point = t.getTopicPoint();
                break;
            }
        }
        items = new ArrayList<String>();
        float score = 0.0f;
        for (; score <= point; ) {
            items.add(score + "");
            score += 0.5;
        }
        return items;
    }

    /**
     * 显示主观题分数修改键盘
     *
     * @param items
     * @param position
     * @param answer
     * @param tempList
     */
    private void showKeyboardDialog(List<String> items, final int position,
                                    final String answer, final ArrayList<SubjectAnswer> tempList) {
        index = position;
        int serialNum = mSubjectList.get(index).getSerialNumber();
        int beginNo = mSubjectList.get(index).getTopic().getTopicBegin();
        int endNo = mSubjectList.get(index).getTopic().getTopicEnd();
        String title = null;
        if (beginNo != endNo) {
            title = " 第" + beginNo + "~" + endNo + "题：" + answer + " 分";
        } else {
            title = " 第" + serialNum + "题：" + answer + " 分";
        }
        mPopupWindow = new KeyboardWindow(mContext, this, title);
        if (answer.trim().equals("")) {
            mPopupWindow.setInputContent("0");
        } else {
            mPopupWindow.setInputContent(answer);
        }
        if (index == tempList.size() - 1) {
            mPopupWindow.setNextText("完成");
        } else if (index == 0) {
            mPopupWindow.setPreviewText("完成");
        }
        mPopupWindow.setNextListener(new KeyboardWindow.OnNextListener() {
            @Override
            public void next() {
                setKeyboardPositionAnswer(index);
                if (index < tempList.size() - 1) {
                    index += 1;
                    setPositionData(tempList);
                    String nextButtonStr = "下一题";
                    if (index == tempList.size() - 1) {
                        nextButtonStr = "完成";
                    }
                    mPopupWindow.setNextText(nextButtonStr);
                    if (index != 0) {
                        mPopupWindow.setPreviewText("上一题");
                    }
                } else {
                    mPopupWindow.dismiss();
                }
            }
        });
        mPopupWindow.setPreviewListener(new KeyboardWindow.OnPreviewListener() {
            @Override
            public void preview() {
                setKeyboardPositionAnswer(index);
                if (index > 0) {
                    index -= 1;
                    setPositionData(tempList);
                    String previewButtonStr = "上一题";
                    if (index == 0) {
                        previewButtonStr = "完成";
                    }
                    mPopupWindow.setPreviewText(previewButtonStr);
                    if (index != tempList.size() - 1) {
                        mPopupWindow.setNextText("下一题");
                    }
                } else {
                    mPopupWindow.dismiss();
                }
            }
        });
        mPopupWindow.showAtLocation(ProofreadCorrectActivity.this.findViewById(R.id.proofread_create_ll),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 设置主观题键盘数据
     *
     * @param answerList
     */
    private void setPositionData(List<SubjectAnswer> answerList) {
        int serialNum2 = mSubjectList.get(index).getSerialNumber();
        String answer2 = answerList.get(index).getAnswer();
        int beginNo = mSubjectList.get(index).getTopic().getTopicBegin();
        int endNo = mSubjectList.get(index).getTopic().getTopicEnd();
        String title2 = null;
        if (beginNo != endNo) {
            title2 = " 第" + beginNo + "~" + endNo + "题：" + answer2 + " 分";
        } else {
            title2 = " 第" + serialNum2 + "题：" + answer2 + " 分";
        }
        mPopupWindow.setTitle(title2);
        if (answer2.trim().equals("")) {
            mPopupWindow.setInputContent("0.0");
        } else {
            mPopupWindow.setInputContent(answer2);
        }
    }

    /**
     * 修改主观题列表数据
     *
     * @param position
     */
    private void setKeyboardPositionAnswer(final int position) {
        String currentAnswer = mPopupWindow.getScore() + "";
        mSubjectList.get(position).setAnswer(currentAnswer);
        mSubjectAdapter.notifyDataSetChanged();
        isUpdate = true;
        // TODO是否是修改后的按钮状态
    }

    /**
     * 获取学生答案请求
     */
    public void getStudentAnswersRequest() {
        if (isInitDataRequest) {
            mLoadDialog = LoadDialog.show(mContext, null, "加载中...", false);
        }
        JsonObjectRequest request = mRequest.getAggregateRequest(mExaminationId, true, true, true,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        getStudentAnswerExaminationListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "加载学生答案失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 获取学生答案监听
     *
     * @param response
     */
    public void getStudentAnswerExaminationListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                // 获取题型
                mTopics = AnswerUtil.getTopics(response);
                // 获取标准答案
                List<Standard> standards = AnswerUtil
                        .getStandardAnswers(response);
                setAnswers(standards);
                if (mStaList == null) {
                    LoadDialog.dismiss(mLoadDialog);
                    MyToast.showShort(mContext, "当前还未设置标准答案，请先设置标准答案！");
                    return;
                }
                // 获取学生的答案
                mClassManages = AnswerUtil.getStudentAnswers(response);
                if (mStudentNo.equals("")) {
                    LoadDialog.dismiss(mLoadDialog);
                    MyToast.showShort(mContext, "学号不存在，请填写学号和答案");
                    setEmptyStudentAnswer();
                    setObjectAnswerToList(false);
                    setSubjectAnswerToList(false);
                    return;
                }
                getStudentAnswerRequest();
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
        } finally {
            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                LoadDialog.dismiss(mLoadDialog);
                MyToast.showShort(mContext, "加载学生答案失败");
            }
        }
    }

    /***
     * 设置空的学生答案string
     */
    private void setEmptyStudentAnswer() {
        StringBuffer objectAnswer = new StringBuffer();
        for (int i = 0; i < mTopics.size(); i++) {
            if (i == mTopics.size() - 1) {
                objectAnswer.append("0");
            } else {
                objectAnswer.append("0,");
            }
        }
        emptyStudentAnswer = objectAnswer.toString();
//        AnswerUtil.objectAnswerToList(objectAnswer, mTopics);
    }

    /**
     * 上传学生答案请求
     */
    private void uploadSingleStudentAnswersRequest() {
        isInitDataRequest = false;
        JsonObjectRequest request = mRequest.uploadSingleStudentAnswersRequest(
                mExaminationId, mExamLastModifiedTime, mClassManages, mStudent,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        uploadStudentAnswerListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRequest.disposeError(mContext, mLoadDialog, error, "修改失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 上传学生答案监听
     *
     * @param response
     */
    private void uploadStudentAnswerListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
//                Student uploadStudent = uploadStudents.getFirst();
//                uploadStudent.setUploadStatus(FragmentStudentAdapter.COMPLETE);
                isUpdate = false;
//                initView();
                configView();
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07071_000001E);
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07072_000012E);
            } else if (resultCode.equals(ResultCode.result_200001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07073_200001E);
            } else if (resultCode.equals(ResultCode.result_200003E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07074_200003E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_07075_300001E);
            } else if (resultCode
                    .equals(ResultCode.result_version_unlike_exception_777777E.resultCode)) {
                MyToast.showShort(mContext, "当前数据已被更改，请刷新后操作");
            } else if (resultCode
                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                MyToast.showShort(mContext, R.string.readcard_070799_999999E);
            } else if (resultCode.equals(ResultCode.result_300017E.resultCode)) {
                MyToast.showShort(mContext, "请录入标准答案");
            } else {
                MyToast.showShort(mContext, "修改失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
        } finally {
            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                LoadDialog.dismiss(mLoadDialog);
            }
        }
    }


    /**
     * 加载学生答案请求
     */
    private void getStudentAnswerRequest() {
        // 发布考试
        JsonObjectRequest request = mRequest.getStudentAnswerRequest(mExaminationId, mStudentNo,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        studentAnswerListener(jsonObject);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        LogUtil.e("上传学生答案失败", volleyError);
                        mRequest.disposeError(mContext, mLoadDialog, volleyError, "加载学生答案失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 获取学生答案监听
     *
     * @param response
     */
    private void studentAnswerListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONObject jsonObject = response.getJSONObject("studentAnswer");
                Gson gson = new Gson();
                mProofreadStudentAnswer = gson.fromJson(jsonObject.toString(),
                        ProofreadStudentAnswer.class);
                if (!isInitDataRequest) {
                    MyToast.showShort(mContext, "修改成功");
                }
                setObjectAnswerToList(true);
                setSubjectAnswerToList(true);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.proofread_11001_300001E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.proofread_11002_300002E);
            } else if (resultCode.equals(ResultCode.result_200025E.resultCode)) {
                MyToast.showShort(mContext, R.string.proofread_11003_200025E);
            } else {
//                MyToast.showShort(mContext, "加载学生答案失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
        } finally {
            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                setEmptyStudentAnswer();
                setObjectAnswerToList(false);
                setSubjectAnswerToList(false);
            }
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 设置标准答案list
     *
     * @param standards
     */
    private void setAnswers(List<Standard> standards) {
        Collections.sort(mTopics, new TopicCollections(false));
        if (standards == null) {
            return;
        }
        ArrayList<Map<String, Object>> answerList = null;
        if (standards != null && standards.size() > 0) {
            answerList = AnswerUtil.answerToStudentList(standards.get(0)
                    .getContent(), mTopics);
        } else {
            answerList = AnswerUtil.answerToStudentList(null, mTopics);
        }
        mStaList.clear();
        mStaList.addAll(answerList);
//        }
    }

    /**
     * 把客观题字符串答案转为list
     */
    private void setObjectAnswerToList(boolean isHaveAnswer) {
        String objectAnswer = "";
        if (mStudentNo.equals("") || !isHaveAnswer) {
            objectAnswer = emptyStudentAnswer;
        } else {
            objectAnswer = mProofreadStudentAnswer.getAnswer().getObjectAnswers();
        }
        ArrayList<ObjectAnswer> objectAnswers;
        objectAnswers = AnswerUtil.objectAnswerToList(objectAnswer, mTopics);
        mObjectList.clear();
        mObjectList.addAll(objectAnswers);
        mObjectAdapter.notifyDataSetChanged();
    }

    /**
     * 把主观题字符串答案转为list
     */
    private void setSubjectAnswerToList(boolean isHaveAnswer) {
        String objectAnswer = "";
        if (mStudentNo.equals("") || !isHaveAnswer) {
            objectAnswer = emptyStudentAnswer;
        } else {
            objectAnswer = mProofreadStudentAnswer.getAnswer().getSubjectAnswers();
        }
        ArrayList<SubjectAnswer> subjectAnswers;
        subjectAnswers = AnswerUtil.answerSubOneList(objectAnswer, mTopics);
        mSubjectList.clear();
        mSubjectList.addAll(subjectAnswers);
        mSubjectAdapter.notifyDataSetChanged();
    }

    /**
     * 设置item答案
     *
     * @param position
     * @param answerDialog
     * @param answer
     */
    private void setPositionAnswer(final int position,
                                   final SingleAnswerDialog answerDialog, String answer) {
        String currentAnswer = answerDialog.getAnswer();
        if (!currentAnswer.equals(answer)) {
            mObjectList.get(position).setAnswer(currentAnswer);
//            mObjectList.clear();
//            mObjectList.addAll(tempObjectList);
            mObjectAdapter.notifyDataSetChanged();
            isUpdate = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            closeAct();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    public void closeAct() {
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.commit_answer_tv:
                commitStudentAnswer();
                break;
            case R.id.proofread_weight_rl:
                if (weightFlag) {
                    LinearLayout.LayoutParams imageLp = new LinearLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT, 0, 4f);
                    mProofreadImageLl.setLayoutParams(imageLp);
                    mStretchIv.setImageDrawable(ResourcesUtil.getDrawable(mContext, R.mipmap.proofread_up));
                    weightFlag = false;
                } else {
                    LinearLayout.LayoutParams imageLp = new LinearLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f);
                    mProofreadImageLl.setLayoutParams(imageLp);
                    mStretchIv.setImageDrawable(ResourcesUtil.getDrawable(mContext, R.mipmap.proofread_down));
                    weightFlag = true;
                }
                break;
        }
    }

    /**
     * 提交学生答案
     */
    private void commitStudentAnswer() {
        String studentNoTemp = mStudentNoTv.getText().toString();
        String studentNameTemp = mStudentNameTv.getText().toString();
        if (!studentNoTemp.equals(mStudentTempNo) || !studentNameTemp.equals(mStudentTempName)) {
            isUpdate = true;
        } else {
            isUpdate = false;
        }
        if (!isUpdate) {
            MyToast.showShort(mContext, "答案没有修改");
            return;
        }
        if (isExceedScore()) {
            return;
        }
        mLoadDialog = LoadDialog.show(mContext, null, "保存中...", false);
        mStudentNo = mStudentNoTv.getText().toString();
        boolean isHaveStudentNo = false;
        for (ClassManage classManage : mClassManages) {
            ArrayList<Student> students = classManage.getStudents();
            for (Student student : students) {
                if (mStudentNo.equals(student.getNumber())) {
                    mStudent = student;
                    isHaveStudentNo = true;
                    break;
                } else {
                    continue;
                }
            }
        }
        if (!isHaveStudentNo) {
            MyToast.showShort(mContext, "该学号不存在");
            LoadDialog.dismiss(mLoadDialog);
            return;
        }
        String content = AnswerUtil.listToObjectAnswer(mObjectList, TopicUtil.getCurrentMaxNo(mTopics));
        String answerStr = AnswerUtil.listOneToAnswer(mSubjectList, mTopics, TopicUtil.getCurrentMaxNo(mTopics));
        mStudent.getAnswer().setSubjectAnswers(answerStr);
        mStudent.getAnswer().setObjectAnswers(content);
        mStudent.setStatus(StudentStatus.I.text);
        uploadSingleStudentAnswersRequest();
    }

    /**
     * 判断设置的分数是否总分
     *
     * @return
     */
    private boolean isExceedScore() {
        boolean isReturn = false;
        float topicTotalScore = 0f;
        for (int i = 0; i < mSubjectList.size(); i++) {
            Topic tp = mSubjectList.get(i).getTopic();
            topicTotalScore = tp.getTopicPoint();
            int startNo = tp.getTopicBegin();
            int endNo = tp.getTopicEnd();
            String score = mSubjectList.get(i).getAnswer();
            if (StringUtil.parseFloat(score, 0f) > topicTotalScore) {
                MyToast.showShort(mContext, "第" + startNo + "~" + endNo + "题超出了总分，请重新录入");
                isReturn = true;
                break;
            }
        }
        return isReturn;
    }

}